import React, { useState, useEffect } from "react";
import { Image as AntdImage } from "antd";
import styles from "./index.less";

const ImageView = ({ src, onClick }: { src: string; onClick: () => void }) => {
  const [style, setStyle] = useState<{}>({ width: "100%", height: "auto" });
  const [backgroundImage, setBackgroundImage] = useState<string>("");
  const ref = React.createRef();

  useEffect(() => {
    loadImage();
  }, [src]);

  const loadImage = () => {
    const img = new Image();

    img.onload = () => {
      const { width, height } = img;
      if (ref.current) {
        const { clientWidth, clientHeight } = ref.current as any;
        if (width / clientWidth < height / clientHeight) {
          setStyle({
            width: "auto",
            height: "100%",
          });
        } else {
          setStyle({
            width: "100%",
            height: "auto",
          });
        }
      }

      setBackgroundImage(src);
    };

    img.src = src;
  };

  return (
    <div
      ref={ref}
      rel="preload"
      className={styles.imageView}
      style={{ backgroundImage: `url(${backgroundImage})` }}
    >
      <AntdImage onClick={onClick} src={src} style={style} preview={false} />
    </div>
  );
};

export default ImageView;
